import { PlayerRank, PlayerPosition } from '@prisma/client'
import { prisma } from '../utils/database'
import { PlayerStatistics, OverviewStatistics, RankStatistic, PositionStatistic } from '../types/api'
import { createDatabaseError } from '../utils/errors'

// 段位标签和颜色配置
const RANK_CONFIG = {
  [PlayerRank.HERALD]: { label: '先锋', color: '#909399' },
  [PlayerRank.GUARDIAN]: { label: '卫士', color: '#67C23A' },
  [PlayerRank.CRUSADER]: { label: '中军', color: '#E6A23C' },
  [PlayerRank.ARCHON]: { label: '统帅', color: '#409EFF' },
  [PlayerRank.LEGEND]: { label: '传奇', color: '#722ED1' },
  [PlayerRank.ANCIENT]: { label: '万古流芳', color: '#F56C6C' },
  [PlayerRank.DIVINE]: { label: '超凡入圣', color: '#FF4D4F' },
  [PlayerRank.IMMORTAL]: { label: '冠绝一世', color: '#FFD700' }
}

// 位置标签配置
const POSITION_CONFIG = {
  [PlayerPosition.CARRY]: { label: '优势路' },
  [PlayerPosition.MID]: { label: '中路' },
  [PlayerPosition.OFFLANE]: { label: '劣势路' },
  [PlayerPosition.SUPPORT]: { label: '辅助' },
  [PlayerPosition.HARD_SUPPORT]: { label: '纯辅助' }
}

// 获取选手统计信息
export const getPlayerStatistics = async (): Promise<PlayerStatistics> => {
  try {
    // 获取总选手数
    const totalPlayers = await prisma.player.count()

    // 获取段位统计
    const rankCounts = await prisma.player.groupBy({
      by: ['rank'],
      _count: {
        rank: true
      }
    })

    // 构建完整的段位统计（包含0数量的段位）
    const rankStatistics: RankStatistic[] = Object.values(PlayerRank).map(rank => {
      const count = rankCounts.find(r => r.rank === rank)?._count.rank || 0
      return {
        rank,
        count,
        label: RANK_CONFIG[rank].label,
        color: RANK_CONFIG[rank].color
      }
    })

    // 获取位置统计
    const positionCounts = await prisma.playerPositionMapping.groupBy({
      by: ['position'],
      _count: {
        position: true
      }
    })

    // 构建位置统计
    const positionStatistics: PositionStatistic[] = Object.values(PlayerPosition).map(position => {
      const count = positionCounts.find(p => p.position === position)?._count.position || 0
      const percentage = totalPlayers > 0 ? (count / totalPlayers) * 100 : 0
      return {
        position,
        count,
        label: POSITION_CONFIG[position].label,
        percentage: Math.round(percentage * 10) / 10 // 保留1位小数
      }
    })

    // 获取MMR统计
    const mmrStats = await prisma.player.aggregate({
      _avg: { highestMmr: true },
      _max: { highestMmr: true },
      _min: { highestMmr: true }
    })

    // 获取中位数MMR
    const players = await prisma.player.findMany({
      select: { highestMmr: true },
      orderBy: { highestMmr: 'asc' }
    })

    let median = 0
    if (players.length > 0) {
      const middle = Math.floor(players.length / 2)
      if (players.length % 2 === 0) {
        median = (players[middle - 1]!.highestMmr + players[middle]!.highestMmr) / 2
      } else {
        median = players[middle]!.highestMmr
      }
    }

    const mmrStatistics = {
      average: Math.round(mmrStats._avg.highestMmr || 0),
      highest: mmrStats._max.highestMmr || 0,
      lowest: mmrStats._min.highestMmr || 0,
      median: Math.round(median)
    }

    return {
      totalPlayers,
      rankStatistics,
      positionStatistics,
      mmrStatistics
    }
  } catch (error) {
    console.error('获取选手统计信息失败:', error)
    throw createDatabaseError('获取选手统计信息失败')
  }
}

// 获取概览统计
export const getOverviewStatistics = async (): Promise<OverviewStatistics> => {
  try {
    const now = new Date()
    const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1)

    // 选手统计
    const [totalPlayers, newPlayersThisMonth] = await Promise.all([
      prisma.player.count(),
      prisma.player.count({
        where: {
          createdAt: {
            gte: startOfMonth
          }
        }
      })
    ])

    // 比赛统计（目前为0，为未来扩展预留）
    const [totalMatches, matchesThisMonth, upcomingMatches] = await Promise.all([
      prisma.match.count(),
      prisma.match.count({
        where: {
          createdAt: {
            gte: startOfMonth
          }
        }
      }),
      prisma.match.count({
        where: {
          startTime: {
            gte: now
          },
          status: 'draft'
        }
      })
    ])

    // 队伍统计（目前为0，为未来扩展预留）
    const [totalTeams, activeTeams] = await Promise.all([
      prisma.team.count(),
      prisma.team.count() // 暂时所有队伍都算活跃
    ])

    return {
      players: {
        total: totalPlayers,
        activeThisMonth: totalPlayers, // 暂时所有选手都算活跃
        newThisMonth: newPlayersThisMonth
      },
      matches: {
        total: totalMatches,
        thisMonth: matchesThisMonth,
        upcoming: upcomingMatches
      },
      teams: {
        total: totalTeams,
        active: activeTeams
      }
    }
  } catch (error) {
    console.error('获取概览统计失败:', error)
    throw createDatabaseError('获取概览统计失败')
  }
}
